from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
from options import options


class Discuz():
    def __init__(self, driver):
        self.driver = driver

    def login(self, username, password):
        self.driver.find_element(By.ID, 'ls_username').clear()
        self.driver.find_element(By.ID, 'ls_username').send_keys(username)
        self.driver.find_element(By.ID, 'ls_password').clear()
        self.driver.find_element(By.ID, 'ls_password').send_keys(password)
        sleep(3)
        self.driver.find_element(By.XPATH, '//*[@id="lsform"]/div/div/table/tbody/tr[2]/td[3]/button/em').click()
        sleep(3)

    def register(self):
        pass

    def post(self, subject, message, username='admin', password='sa'):
        self.login(username, password)
        # 发帖
        self.driver.find_element(By.XPATH, '//*[@id="category_1"]/table/tbody/tr[1]/td[2]/h2/a').click()
        self.driver.find_element(By.ID, 'newspecial').click()
        self.driver.find_element(By.ID, 'subject').clear()
        self.driver.find_element(By.ID, 'subject').send_keys(subject)
        # 注意：嵌套页面的处理
        self.driver.switch_to.frame('e_iframe')
        self.driver.find_element(By.XPATH, '/html/body').clear()
        self.driver.find_element(By.XPATH, '/html/body').send_keys(message)
        # 注意：跳回默认页面
        self.driver.switch_to.default_content()
        self.driver.find_element(By.ID, 'postsubmit').click()
        sleep(3)

    def read(self):
        pass

    def reply(self):
        pass

    def logout(self):
        self.driver.find_element(By.LINK_TEXT, '退出').click()
        sleep(3)


if __name__ == '__main__':
    url = r'http://172.16.36.121/upload/'
    username = 'admin'
    password = 'sa'
    subject = '我的帖子01'
    message = '我的帖子01'
    driver = webdriver.Chrome(options=options)
    driver.get(url)

    discuz = Discuz(driver)
    # discuz.assert(username,password)
    discuz.post(subject, message)
    # discuz.logout()

    driver.quit()
